package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.pojo.DeviceData;
import com.zzyl.nursing.domain.pojo.Room;
import com.zzyl.nursing.domain.vo.BedVo;
import com.zzyl.nursing.domain.vo.DeviceInfo;
import com.zzyl.nursing.domain.vo.RoomVo;
import com.zzyl.nursing.mapper.RoomMapper;
import com.zzyl.nursing.service.IRoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 房间Service业务层处理
 * @author ruoyi
 * @date 2024-04-26
 */
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements IRoomService {
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    /**
     * 查询房间
     * @param id 房间主键
     * @return 房间
     */
    @Override
    public Room selectRoomById(Long id) {
        return getById(id);
    }
    
    /**
     * 查询房间列表
     * @param room 房间
     * @return 房间
     */
    @Override
    public List<Room> selectRoomList(Room room) {
        return roomMapper.selectRoomList(room);
    }
    
    /**
     * 新增房间
     * @param room 房间
     * @return 结果
     */
    @Override
    public int insertRoom(Room room) {
        return save(room) ? 1 : 0;
    }
    
    /**
     * 修改房间
     * @param room 房间
     * @return 结果
     */
    @Override
    public int updateRoom(Room room) {
        return updateById(room) ? 1 : 0;
    }
    
    /**
     * 批量删除房间
     * @param ids 需要删除的房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }
    
    /**
     * 根据楼层 id 获取房间视图对象列表
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsByFloorId(Long floorId) {
        return roomMapper.selectByFloorId(floorId);
    }
    
    
    /**
     * 获取所有房间（负责老人）
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithNurByFloorId(Long floorId) {
        return roomMapper.selectByFloorIdWithNur(floorId);
    }
    
    @Override
    public RoomVo selectRoomVoById(Long id) {
        return this.getBaseMapper()
                   .selectRoomVoById(id);
    }
    
    @Override
    public List<RoomVo> getRoomsWithDeviceByFloorId(Long floorId) {
        // 1-通过相关表查询所有房间：List<RoomVo>
        List<RoomVo> roomVoList=this.getBaseMapper()
                                    .getRoomsWithDeviceByFloorId(floorId);
        if (CollUtil.isEmpty(roomVoList)) {
            return List.of();
        }
        // 2-循环遍历List<RoomVo>找到每一个设备，给每一个设备填充设备最新上报数据：从redis获取然后填充上报数据
        // 2.1拿到redis中所有设备的数据转换一个Map<String deviceId,List<DeviceData>>
        Map<Object, Object> entries=stringRedisTemplate.opsForHash()
                                                       .entries(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (CollUtil.isEmpty(entries)) {
            return roomVoList;
        }
        Map<String, List<DeviceData>> deviceDataMap=entries.entrySet()
                                                           .stream()
                                                           .collect(Collectors.toMap(entry -> entry.getKey()
                                                                                                   .toString(),entry -> JSONUtil.toList(entry.getValue()
                                                                                                                                             .toString(),DeviceData.class)));
        // 2.2对所有房间进行循环遍历，同时遍历房间所有设备、以及房间床上所有设备
        roomVoList.forEach(roomVo -> {
            // 1-该房间所有设备遍历，然后填充对应设备的设备数据
            List<DeviceInfo> roomDeviceList=roomVo.getDeviceVos();
            if (CollUtil.isNotEmpty(roomDeviceList)) {
                // 给每一个设备填充设备数据
                roomDeviceList.forEach(roomDevice -> roomDevice.setDeviceDataVos(deviceDataMap.getOrDefault(roomDevice.getIotId(),List.of())));
            }
            // 2-该房间所有床上所有设备遍历，然后填充对应设备的设备数据
            List<BedVo> bedVoList=roomVo.getBedVoList();
            if (CollUtil.isNotEmpty(bedVoList)) {
                bedVoList.forEach(bedVo -> {
                    List<DeviceInfo> bedDeviceList=bedVo.getDeviceVos();
                    if (CollUtil.isNotEmpty(bedDeviceList)) {
                        // 给每一个设备填充设备数据
                        bedDeviceList.forEach(bedDevice -> bedDevice.setDeviceDataVos(deviceDataMap.getOrDefault(bedDevice.getIotId(),List.of())));
                    }
                });
            }
        });
        return roomVoList;
    }
}
